/** cardComponents
 * [state cardedit 专用 state]
 * 单个 card site 站点操作都放在这里
 * @type {Object}
 */

import { ElMessage } from 'element-plus';
import { createStore } from 'vuex';
import router from '@/router';
import pagesServer from '@/api/pages';
import userServer from '@/api/user';
import { CardSiteDataDefault, BUSINESS_NO_CARD } from '@/views/card/js/data/cardSiteData';
// import { isArray, isHasOwnProperty } from '@/utils/public.js';
import panelComponents from './panel-components';



const state = {
  siteData: {  // card site data
    id: '',
    attrs: {  // pageInfo
      // ..._.cloneDeep(CardSiteDataDefault.attrs),
      desc: '',
    },
    pages: [],
    controls: [],  // cardLists
    uids: [],  // 统计 cardLists 所有相关 uids
    mids: [],  // 统计 cardLists 所有相关 mids
  },
  sitePreshowData: {  // card site preShow data
    status: '',
    // pageurl: '',  // 站点链接
    // qrcode: '',  // 站点链接的二维码
    // update_time: '',  // 更新时间
  },
  curTarget: {  // 当前编辑 item; ⚠️注意：仅暂存 itemId 以及 parentId
    itemId: '',
    parentId: '',
  },
  mgSitePreview: {  // 站点预览配置
    isActive: false,  // show / hide
  },
  curPage: 0,  // 当前页 pages[0]
  curPageData: [],  // 当前页 data
  curLayoutType: 'PAGE',  // PAGE / PANEL
};

const getters = {};

const actions = {
  createCardSite({dispatch, commit, state}, params) {  /* 创建cardList站点 */
    // 1. 创建新的 cardSite 站点，由后端生成 id ，name
    const newCreateSiteParams = {
      id: '',
      tag: params.type,
    };
    pagesServer.createSite(newCreateSiteParams, (cData) => {
      // console.log('cData: ', cData);

      // 2. 初始化站点数据
      commit('initCardSiteData', cData);

      // 3. 保存站点数据
      dispatch('saveCardSite').then(() => {
        // 4. 跳转至编辑页面
        const cardSiteId = state.siteData.id;
        router.push({ name: 'cardedit', params: { id: cardSiteId } });
      })
    });
  },
  async saveCardSite({commit, state}, params) {
    // 1. update uids / mids
    // TODO: 检查 uids / mids 是否填写？
    commit('updateUidsAndMids');

    // 2. 清空 mblog
    commit('clearCardMblog');

    // 3. 保存站点数据
    // console.log('state.siteData: ', state.siteData);
    const newSaveSiteDataParams = {
      ...state.siteData,
    };
    await pagesServer.savePageDatas(newSaveSiteDataParams, (sData) => {
      // console.log('sData: ', sData);

      // 4. callback
      if(params && params.callback) params.callback(sData);
    });
  },
  async getCardSite({commit}, params) {  /* get CardSite 站点数据 */
    // 1. 获取 cardsite 站点数据
    const newGetSiteParams = {
      id: params.id,
    };
    await userServer.getSiteData(newGetSiteParams, (gData) => {
      // console.log('getSiteData gData: ', gData);

      // 2. update card site data
      commit('updateCardSiteData', gData);

      // 3. uadate curPageData
      commit('updateCurPage', 0)
    });
  },
  async getCardSitePreshow({state, commit}, params) {  /* get CardSite preshow 站点预览数据 */
    // 1. 获取 cardsite preshow 站点预览数据
    const newGetSitePreshowParams = {
      site_id: params.id,
    };
    await userServer.getTempPreviewUrl(newGetSitePreshowParams, (gData) => {
      // 2. update card site preshow data
      commit('updateCardSitePreshowData', gData);

      // 3. update card site data qrcode
      if(!state.siteData.attrs.qrcode || state.siteData.attrs.qrcode == '') {
        commit('updateCardSiteData', {
          ...state.siteData,
          attrs: {
            ...state.siteData.attrs,
            qrcode: gData.qrcode,
          },
        })
      }

      // console.log('getTempPreviewUrl gData: ', gData);
    });
  },
  async getCardSitePreshow4Qrcode({state, commit}, params) {  /* get CardSite preshow 站点预览数据 */
    // 1. 获取 cardsite preshow 站点预览数据
    const newGetSitePreshowParams = {
      site_id: params.id,
    };
    await userServer.getTempPreviewUrl(newGetSitePreshowParams, (gData) => {
      // 2. update card site preshow data
      commit('updateCardSitePreshowData', gData);

      // 3. update card site data qrcode
      commit('updateCardSiteData', {
        ...state.siteData,
        attrs: {
          ...state.siteData.attrs,
          qrcode: gData.qrcode,
        },
      })

      // console.log('getTempPreviewUrl gData: ', gData);
    });
  },

  /* 拷贝站点 */
  createCopySite({dispatch, commit, state}, params) {
    // 拷贝逻辑需要重新梳理
    // 1. itemid 改变
    // 2. 参数
    // console.log(params);

    // 0.
    if(!params || !params.data) return;

    // 1. 创建copy的 cardSite 站点，由后端生成 id ，name
    const newCreateSiteParams = {
      id: '',
      tag: params.type,
    };
    pagesServer.createSite(newCreateSiteParams, (cData) => {
      // 2. container_id
      // const container_id = BUSINESS_NO_CARD + '_-_' + cData.id;

      // 3. 初始化站点数据
      commit('copyCardSiteData', {cData: cData, params: params});

      // 4. 保存站点数据
      dispatch('saveCardSite').then(() => {
        // 6. 跳转至编辑页面
        const cardSiteId = state.siteData.id;
        router.push({ name: 'cardedit', params: { id: cardSiteId } });
      })
    });
  },


  /* common current select item */
  updateCurTarget({commit}, params) {
    commit('updateCurTarget', params);
  },

  /* current page */
  updateCurPage({commit}, params) {
    commit('updateCurPage', params);
  },

  /* update site data */
  updateCardLists({commit}, params) {
    commit('updateCardLists', params);
  },
  updateCardPageInfo({commit}, params) {
    commit('updateCardPageInfo', params);
  },
  async onlineSite({state, commit}, params) {  /* status: online 2-下线，1-上线 */
    // 1. 上/下线
    const newOnlineParams = {
      site_id: params.id,
      online: params.status,
    };
    await userServer.onlineSite(newOnlineParams, () => {
      // 2. update card site preshow data
      commit('updateCardSitePreshowData', {
        ...state.sitePreshowData,
        status: params.status,
      });
    });
  },
  handler4AddPage({commit}) {  /* add page */
    commit('handler4AddPage');
  },
  updatePages({commit}, params) {  /* 更新 pages */
    commit('updatePages', params);
  },
  updateCardSiteData({commit}, params) {  /* update card site data */
    commit('updateCardSiteData', params);
  },
  handler4AddPanel({commit}) {
    commit('handler4AddPanel');
  },
  updatePanels({commit}, params) {
    commit('updatePanels', params);
  },
  updatePanelLists({commit}, params) {
    commit('updatePanelLists', params);
  },

  /* generate Qrcode */
  // async generateQrcode({commit}, params) {
  //   const aaa = await pagesServer.generateQrcode({
  //     url: params.url,
  //     size: params.size,
  //     logo: params.logo,
  //     site_id: params.site_id,
  //   });
  //
  //   console.log(aaa);
  // },
  recoverSiteQrcode({commit}, params) {
    const newParams = {
      site_id: params.site_id,
    };
    userServer.recoverSiteQrcode(newParams, (data) => {
      // recoverSiteQrcode
      commit("recoverSiteQrcode", data);

      // callback
      if(params.callback) params.callback(data);
    })
  },

  /* 预览 */
  updateMgSitePreview({commit}, params) {
    commit('updateMgSitePreview', params);
  },
};

const mutations = {
  /* show message */
  showMessage(state, {msg, type}){
    ElMessage({
      message: msg,
      type: type,
    });
  },

  /* data */
  initCardSiteData(state, data) {  /* 初始化cardList站点 */
    // console.log('cardList站点数据：', data);
    let newCardSiteData = _.cloneDeep(CardSiteDataDefault);  // 深拷贝default 初始数据
    let newAllShare = {
      ...newCardSiteData.attrs.share.allShare,
      title: data.name,
    };
    newCardSiteData = {
      ...newCardSiteData,
      id: data.id,
      attrs: {
        ...newCardSiteData.attrs,
        containerid: BUSINESS_NO_CARD + '_-_' + data.id,
        share_containerid: BUSINESS_NO_CARD + '_-_' + data.id,
        h5Type: data.tag,
        share: {
          ...newCardSiteData.attrs.share,
          allShare: newAllShare,
        },
      },
      pages: [[]],
    };
    state.siteData = newCardSiteData;
  },
  copyCardSiteData(state, {cData, params}) {
    // 1. copy data <= params.data(old data)
    let newCardSiteData = _.cloneDeep(params.data);  // 深拷贝数据
    newCardSiteData = {
      ...newCardSiteData,
      id: cData.id,
      attrs: {
        ...newCardSiteData.attrs,
        containerid: BUSINESS_NO_CARD + '_-_' + cData.id,
        share_containerid: BUSINESS_NO_CARD + '_-_' + cData.id,
        h5Type: cData.tag,
        copy_from: params.data.id,
      },
    };

    // 2. pages
    const _copyItem = (item, oldStr, newStr) => {
      return item && {
        ..._.cloneDeep(item),
        ...(item.card_type == 2001 ? {
          card_id: item.card_id.replaceAll(oldStr, newStr),
        } : null),
        itemid: item.itemid.replace(oldStr, newStr),
      };
    };
    let newPage = newCardSiteData.pages && newCardSiteData.pages.map((page) => {
      return page && page.map((item) => {
        if(item.card_type == 11 || item.card_type == 'JY0001') {
          return {
            ..._copyItem(item, params.data.id, cData.id),
            card_group: item.card_group && item.card_group.map((child_item) => {
              return _copyItem(child_item, params.data.id, cData.id);
            }),
          };
        }
        else if(item.card_type == 86) {
          return {
            ..._copyItem(item, params.data.id, cData.id),
            sub_cards: item.sub_cards && item.sub_cards.map((child_item) => {
              return _copyItem(child_item, params.data.id, cData.id);
            }),
          };
        }
        else {
          return _copyItem(item, params.data.id, cData.id);
        }
      });
    });
    newCardSiteData = {
      ...newCardSiteData,
      pages: newPage,
    };
    state.siteData = newCardSiteData;
  },
  updateCardSiteData(state, data) {
    // 1. update card site data
    state.siteData = data;

    // 2. update cuePageData
    state.curPageData = state.siteData.pages[state.curPage];
  },
  updateCardSitePreshowData(state, data) {  /* update sitePreshowData */
    state.sitePreshowData = data;
  },

  /* common current select item */
  updateCurTarget(state, data) {
    state.curTarget = data;
  },

  /* current page */
  updateCurPage(state, data) {
    // 1. update curPage
    state.curPage = data;

    // 2. update cuePageData
    state.curPageData = state.siteData.pages[data];
  },

  /* update site data */
  updateCardLists(state, data) {
    // 1. update curPageData
    state.curPageData = data;

    // 2. update pages
    state.siteData.pages.splice(state.curPage, 1, data);

    // Vue.set(state.siteData.pages, state.curPage, data);
  },
  updateCardPageInfo(state, data) {
    state.siteData.attrs = data;
  },
  updateUidsAndMids(state) {
    // 1. 收集 uids / mids
    let arrUids = [];
    let arrMids = [];

    // 2. handlerUidsAndMids
    const handlerUidsAndMids = (card) => {
      if(card.card_type == 59) {
        handlerUidsAndMids(card.left_element);
        handlerUidsAndMids(card.right_element);
      }
      else if(card.card_type == 88) {
        handlerUidsAndMids(card.left_element);
        handlerUidsAndMids(card.right_element);
      }
      else {
        if(typeof card.Idx_uid == 'string' && card.Idx_uid != '' && arrUids.indexOf(card.Idx_uid) == -1)
          arrUids.push(card.Idx_uid);
        if(typeof card.Idx_mid == 'string' && card.Idx_mid != '' && arrMids.indexOf(card.Idx_mid) == -1)
          arrMids.push(card.Idx_mid);
      }
    };

    // 3. 循环遍历
    state.siteData.pages && state.siteData.pages.forEach((cardLists) => {
      cardLists.forEach((card) => {
        handlerUidsAndMids(card);

        if(card.card_type == 11) {
          card.card_group && card.card_group.forEach((cardGroupChild) => {
            handlerUidsAndMids(cardGroupChild);
          });
        }
        else if(card.card_type == 'JY0001') {
          card.card_group && card.card_group.forEach((cardGroupChild) => {
            if(cardGroupChild && cardGroupChild['obj_52'] && cardGroupChild['obj_52']['item'])
              handlerUidsAndMids(cardGroupChild['obj_52']['item']);
          });
        }
      });
    });

    // 2. update state.siteData.uids / state.siteData.mids
    state.siteData.uids = arrUids;
    state.siteData.mids = arrMids;
  },
  clearCardMblog(state) {
    // 0. handlerClearCardMblog
    const handlerClearCardMblog = (card) => {
      if(card.card_type == 9) card.mblog = {};
      if(card.card_type == 59) {
        card.left_element.mblog = {};
        card.right_element.mblog = {};
      }
      if(card.card_type == 81) card.mblog = {};
      if(card.card_type == 88) {
        card.left_element.mblog = {};
        card.right_element.mblog = {};
      }
      if(card.card_type == 124) {
        card.lists && card.lists.length > 0 && card.lists.map((child_item) => {
          child_item.statuses = [];
          return child_item;
        })
      }
    };

    // 1. 清空 mblog
    state.siteData.pages && state.siteData.pages.map((cardLists) => {
      return cardLists.map((card) => {
        handlerClearCardMblog(card);

        if(card.card_type == 11) {
          card.card_group && card.card_group.forEach((cardGroupChild) => {
            handlerClearCardMblog(cardGroupChild);

            return cardGroupChild;
          });
        }

        return card;
      });
    });
  },
  handler4AddPage(state) {  // 添加页
    state.siteData.pages.push([]);
  },
  updatePages(state, data) {
    state.siteData.pages = data;
  },
  handler4AddPanel(state) {  // 添加弹层
    if (!state.siteData.panels) state.siteData.panels = [];
    state.siteData.panels.push([]);
  },
  updatePanels(state, data) {
    if (!state.siteData.panels) state.siteData.panels = [];
    state.siteData.panels = data;
  },
  updatePanelLists(state, {data, index}) {
    state.siteData.panels.splice(index, 1, data);
  },

  /* generate Qrcode */
  recoverSiteQrcode(state, data) {  /* qrcoderefresh */
    //online 2-下线，1-上线
    let qrData = data[state.siteData.id]
    state.sitePreshowData.qrcode = state.sitePreshowData.status == 1 ? qrData.online : qrData.tmp
  },

  /* 预览 */
  updateMgSitePreview(state, data) {
    state.mgSitePreview = data;
  },

  /* beforeUnmount */
  clear(state, data) {
    // clear cardComponents
    state.siteData = {
      id: '',
      attrs: {
        desc: '',
      },
      pages: [],
      controls: [],
      uids: [],
      mids: [],
    };
    state.sitePreshowData = {
      status: '',
    };
    state.curTarget = {
      itemId: '',
      parentId: '',
    };
    state.mgSitePreview = {
      isActive: false,
    };
    state.curPage = 0;
    state.curPageData = [];
    state.curLayoutType = 'PAGE';
  },
};

export default {
  namespaced: true,
  state: state,
  getters: getters,
  actions: actions,
  mutations: mutations,
  modules: {
    panelComponents
  }
};
